import { MiddlewareCreater, Route, createAuthHelper } from 'f2e-server3'
import * as apis from './apis'

const helper = createAuthHelper()
const app: MiddlewareCreater = {
    name: 'apis',
    mode: ['dev', 'prod'],
    execute: async (conf) => {
        const route = new Route(conf)
        Object.entries(apis).forEach(([key, fn]) => {
            route.on(`api/${key}`, function (_body, ctx) {
                const params = new URLSearchParams(ctx.req.getQuery())
                const body = _body || {}
                params.forEach((v, k) => {
                    body[k] = v
                })
                return fn(body, {
                    ...ctx,
                    loginUser: helper.getLoginUser(ctx)?.user,
                })
            })
        })
        return {
            onRoute: route.execute,
        }
    }
}
export default app
